package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

public class SecurityUserService implements UserDetailsService {
    @Reference
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user =  userService.findUserByUserName(username);
        if (user == null) {
            return null;
        }
        String password = user.getPassword();
        List<GrantedAuthority> roles = new ArrayList<>();
        List<String> keywords = userService.getAuthorityByUserId(user.getId());
        if (keywords != null) {
            for (String keyword : keywords) {
                roles.add(new SimpleGrantedAuthority(keyword));
            }
        }
        return new org.springframework.security.core.userdetails.User(username,password,roles);
    }

}
